<template>
    <Modal v-model="visible" :title="title" @on-ok="ok" :mask-closable="false">
        <Form ref="form" :model="form" :rules="formRules" :label-width="100" onsubmit="return false">
            <FormItem label="充值金额" prop="amount">
                <Input number v-model="form.amount"/>
            </FormItem>
            <FormItem label="备注" prop="remark">
                <Input type="textarea" :rows="4" v-model="form.remark"/>
            </FormItem>
        </Form>

        <div slot="footer">
            <Button type="text" size="large" @click.native="cancel">取消</Button>
            <Button type="primary" size="large" :loading="loading" @click.native="ok">确定</Button>
        </div>
    </Modal>
</template>

<script>
    import api from '../../api';

    export default {
        props: ['getData'],
        data () {
            return {
                visible: false,
                loading: false,
                title: '',
                form: {},
                balanceRecords: [],
                formRules: {
                    amount: [
                        {required: true, type: 'number', message: '金额不能为空并且必须为数字', trigger: 'blur'},
                        {type: 'number', min: 1, message: '金额不能小于1', trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {
            ok () {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.loading = true;
                        let request;
                        this.balanceRecords.forEach(item => item.amount = this.form.amount);
                        this.balanceRecords.forEach(item => item.remark = this.form.remark);
                        request = api.recharge(this.balanceRecords);
                        request.then(data => {
                            this.loading = false;

                            if (data.code === 0) {
                                this.getData();
                                this.visible = false;
                            }
                        });
                    }
                });
            },
            open (title, ids) {
                this.$refs.form.resetFields();
                this.visible = true;
                this.title = title;

                this.balanceRecords = ids;
                this.balanceRecords.forEach(item => item.type = 1);

            },
            cancel () {
                this.visible = false;
            }
        }
    };
</script>
